//
//  PhotoBrowserAnimator.swift
//  DXWeibo
//
//  Created by dx on 17/2/22.
//  Copyright © 2017年 dx. All rights reserved.
//

import UIKit

private var isPresent = false

// 照片浏览器的动画器 - 提供转场动画的一切细节
class PhotoBrowserAnimator: NSObject, UIViewControllerTransitioningDelegate {
    
    // 返回提供真正实现展现动画对象
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresent = true
        
        return self
    }
    
    // 返回提供真正实现展现动画对象
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresent = false
        
        return self
    }
}

// MARK: - UIViewControllerAnimatedTransitioning - 具体的动画实现功能逻辑
extension PhotoBrowserAnimator: UIViewControllerAnimatedTransitioning {
    
    // 动画的执行时长
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.25
    }
    
    
    /// 指定具体的动画逻辑 - 一旦实现了此方法，系统默认的转场失效，所有的动画需要程序员来提供
    ///
    /// 负责 present / dismiss 的动画效果
    ///
    /// - Parameter transitionContext: 转场上下文，提供转场所需相关内容
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        isPresent ? presentTransition(using: transitionContext) : dismissTransition(using: transitionContext)
        
    }
    
    // MARK: - 动画函数
    private func presentTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        // 1. 目标视图
        let toView = transitionContext.view(forKey: .to)!
        
        // 2. 容器视图 - 动画代码实现的舞台
        let containerView = transitionContext.containerView
        
        // 3. 将目标视图添加到容器视图
        containerView.addSubview(toView)
        
        // 4. 动画代码
        toView.alpha = 0
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { 
            toView.alpha = 1
        }) { (_) in
            
            // 5. 告诉上下文转场动画结束
            transitionContext.completeTransition(true)
        }
        
    }
    
    private func dismissTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        // 1. 照片浏览视图
        let fromView = transitionContext.view(forKey: .from)
        
        // 2. 动画代码
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { 
            fromView?.alpha = 0
        }) { (_) in
            
            // 3. 删除视图
            fromView?.removeFromSuperview()
            
            // 4. 结束转场
            transitionContext.completeTransition(true)
        }
        
    }
}



